from datetime import timedelta, date
from flask_jwt_extended import create_access_token
from sqlalchemy import select

from model import User, db, UserConfig, StudyPlan, ChatSession, Message, Note, Translation
from tools.chat import get_plan, chat, get_summary, translate, chat_with_question


class UserService(object):
    def login(self, args):
        username = args.get("username")
        password = args.get("password")
        if not username or not password:
            return False, '用户名和密码不能为空', None
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            access_token = create_access_token(identity=user.id, expires_delta=timedelta(hours=24))
            return True, "登录成功", {'access_token': access_token,"user_id":user.id}
        else:
            return False, '用户名或密码错误', None

    def forget_password(self, args):
        username = args.get("username")
        password = args.get("password")
        email = args.get("email")
        if not username or not password or not email:
            return False, '用户名和密码不能为空', None
        user = User.query.filter_by(username=username).first()
        if user and user.email == email:
            user.set_password(password)
            db.session.commit()
            access_token = create_access_token(identity=user.id, expires_delta=timedelta(hours=24))
            return True, "重置密码成功", {'access_token': access_token}
        else:
            return False, '用户名或邮箱错误', None

    def register(self, args):
        username = args.get("username")
        email = args.get("email")
        password = args.get("password")
        if not username or not email or not password:
            return False, '用户名和密码不能为空', None
        user = User.query.filter_by(username=username).first()
        if user:
            return False, '用户名已存在', None
        new_user = User(username=username, email=email)
        new_user.set_password(password)
        db.session.add(new_user)
        db.session.commit()
        access_token = create_access_token(identity=new_user.id, expires_delta=timedelta(hours=24))
        return True, "注册成功", {'access_token': access_token}


class UserConfigService(object):
    def update_user_config(self, args):
        user_id = args.get("user_id")
        avatar = args.get("avatar")
        bio = args.get("bio")
        birth_date = args.get("birth_date")
        birth_date = date.fromisoformat(birth_date)
        # 插入数据时使用date对象
        gender = args.get("gender")
        location = args.get("location")
        if not user_id:
            return False, '用户ID不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        if user.user_config is None:
            user.user_config = UserConfig(user_id=user_id)
        user.user_config.avatar = avatar
        user.user_config.bio = bio
        user.user_config.birth_date = birth_date
        user.user_config.gender = gender
        user.user_config.location = location
        db.session.commit()
        return True, "更新或创建成功", user.user_config.to_json()

    def get_user_config(self, args):
        user_id = args.get("user_id")
        if not user_id:
            return False, '用户ID不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        data =user.user_config.to_json()
        data["username"]=user.username
        return True, "获取用户配置成功",data


class StudyPlanService:
    def generate_study_plan(self, args):
        user_id = args.get('user_id')
        subject = args.get('subject')
        goal = args.get('goal')
        duration = args.get('duration')
        plan = get_plan(subject, goal, duration)
        study_plan = StudyPlan(subject=subject, goal=goal, duration=duration, plan=plan, user_id=user_id)
        db.session.add(study_plan)
        db.session.commit()
        return True, "生成学习计划成功", {"plan": plan}


class ChatService:
    def start_chat(self, args):
        user_id = args.get("user_id")
        if not user_id:
            return False, '用户ID不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        chat_session = ChatSession(user_id=user_id)
        db.session.add(chat_session)
        db.session.commit()
        return True, "开始聊天成功", {"chat_session_id": chat_session.id}

    def get_history(self, args):
        user_id = args.get("user_id")
        if not user_id:
            return False, '用户ID不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        chat_sessions = ChatSession.query.filter_by(user_id=user_id).all()
        chat_sessions =[chat_session.to_json() for chat_session in chat_sessions]
        return True, "获取聊天记录成功", {"chat_sessions": chat_sessions}

    def chat(self, args):
        chat_session_id = args.get("chat_session_id")
        user_id = args.get("user_id")
        question = args.get("question")
        print(chat_session_id)
        chat_session = ChatSession.query.filter_by(id=chat_session_id).first()
        print(chat_session)
        history=""
        if  chat_session:
            chat_session = ChatSession(id=chat_session_id,user_id=user_id)
            messages = Message.query.filter_by(chat_session_id=chat_session_id).all()
            print(messages)
            print(1111)
            history = [message.question + ": " + message.answer+"\n" for message in messages]
            print(222)
        print(333)
        response = chat_with_question(question, history)
        message = Message(chat_session_id=chat_session_id, question=question, answer=response)
        db.session.add(message)
        db.session.commit()
        return True, "聊天成功", {"response": response}

    def get_history_detail(self, args):
        chat_session_id = args.get("chat_session_id")
        if not chat_session_id:
            return False, '聊天记录ID不能为空', None
        chat_session = ChatSession.query.filter_by(id=chat_session_id).first()
        if not chat_session:
            return False, '聊天记录不存在', None
        messages = Message.query.filter_by(chat_session_id=chat_session_id).all()
        messages = [message.to_json() for message in messages]
        return True, "获取聊天记录成功", {"messages": messages}

    def delete_chat(self, args):
        chat_session_id = args.get("chat_session_id")
        if not chat_session_id:
            return False, '聊天记录ID不能为空', None
        messages = Message.query.filter_by(chat_session_id=chat_session_id).all()
        for message in messages:
            db.session.delete(message)
            db.session.commit()
        chat_session = ChatSession.query.filter_by(id=chat_session_id).first()
        if not chat_session:
            return False, '聊天记录不存在', None
        db.session.delete(chat_session)
        db.session.commit()
        return True, "删除聊天记录成功", None

    def search_chat(self, args):
        chat_title = args.get("chat_title")
        if not chat_title:
            return False, '聊天记录标题不能为空', None
        stmt = select(ChatSession).where(ChatSession.chat_title.ilike(chat_title))
        chat_sessions = db.session.execute(stmt).scalars().all()
        if chat_sessions:
            return True, "搜索聊天记录成功", {"chat_sessions": chat_sessions}
        return False, "搜索聊天记录失败", None


class NoteService:
    def save_note(self, args):
        user_id = args.get("user_id")
        title = args.get("title")
        note_id = args.get("note_id")
        content = args.get("content")
        summary = get_summary(content)
        if not user_id or not title or not content:
            return False, '用户ID、标题和内容不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        if note_id and Note.query.filter_by(id=note_id).first():
            note = Note.query.filter_by(id=note_id).first()
        else:
            note = Note()
        note.user_id = user_id
        note.title = title
        note.content = content
        note.summary = summary
        db.session.add(note)
        db.session.commit()
        return True, "保存笔记成功", {"summary": summary}

    def search_note(self, args):
        title = args.get("title")
        if not title:
            return False, '标题不能为空', None
        stmt = select(Note).where(Note.title.ilike(title))
        notes = db.session.execute(stmt).scalars().all()
        notes = [note.to_json() for note in notes]
        if notes:
            return True, "搜索笔记成功", {"notes": notes}
        return False, "搜索笔记失败", None

    def get_all_notes(self, args):
        user_id = args.get("user_id")
        if not user_id:
            return False, '用户ID不能为空', None
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return False, '用户不存在', None
        notes = Note.query.filter_by(user_id=user_id).all()
        notes = [note.to_json() for note in notes]
        return True, "获取笔记成功", {"notes": notes}

    def delete_note(self, args):
        note_id = args.get("note_id")
        if not note_id:
            return False, '笔记ID不能为空', None
        note = Note.query.filter_by(id=note_id).first()
        if not note:
            return False, '笔记不存在', None
        db.session.delete(note)
        db.session.commit()
        return True, "删除笔记成功", None

    def get_note(self, args):
        note_id = args.get("note_id")
        if not note_id:
            return False, '笔记ID不能为空', None
        note = Note.query.filter_by(id=note_id).first()
        if not note:
            return False, '笔记不存在', None
        return True, "获取笔记成功", {"note": note.to_json()}

    def update_note(self, args):
        note_id = args.get("note_id")
        title = args.get("title")
        content = args.get("content")
        summary =  args.get("summary")
        if not note_id or not title or not content:
            return False, '笔记ID、标题和内容不能为空', None
        note = Note.query.filter_by(id=note_id).first()
        if not note:
            return False, '笔记不存在', None
        note.title = title
        note.content = content
        note.summary = summary
        db.session.commit()
        return True, "更新笔记成功", {"summary": summary}

    def generate_summary(self, args):
        content = args.get("content")
        summary = get_summary(content)
        return True, "生成摘要成功", {"summary": summary}



class TranslationService:
    def translate_text(self, args):
        user_id = args.get("user_id")
        source_language = args.get("source_language")
        target_language = args.get("target_language")
        original_text = args.get("original_text")
        translated_text = translate(original_text, source_language, target_language)
        if translated_text:
            translation = Translation()
            translation.source_language = source_language
            translation.target_language = target_language
            translation.original_text = original_text
            translation.translated_text = translated_text
            translation.user_id = user_id
            db.session.add(translation)
            db.session.commit()
            return True, "翻译成功", {"translated_text": translated_text}
        return False, "翻译失败", None
